package j.todo;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TodoLActivity extends ListActivity {
	static final String C0L1 = "line";
	static final String C0L2 = "time";
	static final String C0L3 = "prior";
	static final int DATE_DIALOG_ID = 0;
	public int rate;
	private TextView mDateDisplay;
	private Button mPickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int t;
	private SimpleCursorAdapter adapter;
	private TextView text;
	private EditText edit;
	public DBAdapter db;

	public void onCreate(Bundle savedInstancesState) {
		super.onCreate(savedInstancesState);
		setContentView(R.layout.main);
		// db = new DBAdapter(this);
		// db.open();
		// Cursor cc = db.fetchAllMemo();
		// while(cc.moveToNext()){
		// Toast.makeText(this, cc.getString(3), 1000).show();
		// }
		// db.close();
		//

		// TODO 날짜 dialog

		mDateDisplay = (TextView) findViewById(R.id.dateDisplay);

		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		updateDisplay();

		// 메인화면 리스트, 입력

		text = (TextView) findViewById(R.id.textView1);
		; // Todo list number
		edit = (EditText) findViewById(R.id.edit); // input

		((Button) findViewById(R.id.btnAdd1)).setOnClickListener(listener);
		((Button) findViewById(R.id.btnAdd2)).setOnClickListener(listener);
		((Button) findViewById(R.id.btnTot)).setOnClickListener(listener);
		((Button) findViewById(R.id.btnrank)).setOnClickListener(listener);

		((Button) findViewById(R.id.btnTot2))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(getApplicationContext(),
								SBAttachActivity.class);
						startActivity(intent);
					}
				});

		// setEnabled(false);

	}

	@Override
	protected void onResume() {
		super.onResume();

		db = new DBAdapter(this);
		db.open();
		Cursor c = db.fetchAllMemo();
		startManagingCursor(c);

		// String[] from = new String[] { BaseColumns._ID,C0L1, C0L2};
		String[] from = new String[] { C0L3, C0L1, C0L2 };
		// int[] to = new int[] { R.id.id, R.id.memo, R.id.time};
		int[] to = new int[] { R.id.prior, R.id.memo, R.id.time };

		adapter = new SimpleCursorAdapter(this, R.layout.row, c, from, to); //
		setListAdapter(adapter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		db.close();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		final TextView t = (TextView) v.findViewById(R.id.memo);
		edit.setText(t.getText());
		text.setText(Long.toString(id));

		String str1 = edit.getText().toString();
		// id string
		final String id2 = text.getText().toString();

		//
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(str1 + "를(을) 다했습니까? ?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Toast.makeText(getBaseContext(),
										t.getText() + " 완료!!",
										Toast.LENGTH_LONG).show();
								db.delMemo(id2);

								edit.setText("");

								Cursor c = db.fetchAllMemo();
								startManagingCursor(c);
								adapter.changeCursor(c);

							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

		// setEnabled(true);

	}

	private void setEnabled(boolean enabled) {
		((Button) findViewById(R.id.btnAdd2)).setEnabled(enabled);

		// setEnabled (button show up)
	}

	Button.OnClickListener listener = new View.OnClickListener() {
		public void onClick(View view) {
			String id = text.getText().toString(); // 순번
			String str = edit.getText().toString(); // 내용
			String strdate = mDateDisplay.getText().toString(); // 날짜
			String strR = "A";

			switch (view.getId()) {
			case R.id.btnAdd1:
				if (str.length() != 0) {
					db.addMemo(str, strdate, strR);
					Toast.makeText(getBaseContext(), str + " 가(이) 등록되었습니다.",
							Toast.LENGTH_SHORT).show();
					break;
				} else {
					Toast.makeText(getBaseContext(), "내용을 입력하세요.",
							Toast.LENGTH_SHORT).show();

				}

				text.setText("");
				edit.setText("");
				break;

			case R.id.btnAdd2:
				showDialog(DATE_DIALOG_ID);
				if (str.length() != 0) {
					strdate = mDateDisplay.getText().toString();
					// db.addMemo(str,strdate,strR );
					db.addMemo(str, strdate, "B");
				}
				// 날짜
				// stdate 에 날짜정보 저장

				text.setText("");
				edit.setText("");

				break;
			case R.id.btnTot:
				Intent totlist = new Intent(TodoLActivity.this, totlist.class);
				startActivity(totlist);

				break;

			case R.id.edit:
				// setEnabled(true);
				break;

			case R.id.btnrank:

				final CharSequence[] items = { "A", "B", "C" };

				AlertDialog.Builder builder = new AlertDialog.Builder(
						TodoLActivity.this);
				builder.setTitle("얼마나 중요한가??");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						String strR = (String) items[item];
						String strdate = mDateDisplay.getText().toString();
						String str = edit.getText().toString();
						db.addMemo(str, strdate, strR);
						text.setText("");
						edit.setText("");

					}
				});
				AlertDialog alert = builder.create();
				alert.show();

				// Toast.makeText(getBaseContext(), "우선순위",
				// Toast.LENGTH_LONG).show();
				break;

			default:
				Toast.makeText(getBaseContext(), " Error", Toast.LENGTH_LONG)
						.show();

			}
			//
			// text.setText("");
			// edit.setText("");
			// setEnabled(false);

			Cursor c = db.fetchAllMemo();
			startManagingCursor(c);
			adapter.changeCursor(c);

		}
	};

	/** Called when the activity is first created. */

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	// updates the date in the TextView
	private void updateDisplay() {
		mDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mYear).append("-").append(mMonth + 1).append("-")
				.append(mDay));

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// 여기다 날짜 받기
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

}
